<template>
  <div>
    <div class="bg">
      <iframe
        src="/static/html/index.html"
        width="100%"
        height="100%"
        frameborder="0"
        name="showHere"
      ></iframe>
    </div>
    <div class="login">
      <p class="title">{{title}}</p>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="ruleForm">
        <el-form-item prop="username">
          <el-input
            class="inps"
            :readonly="readonly"
            @blur="onBlur"
            @focus="onFocus"
            v-model="ruleForm.username"
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            class="inps"
            @blur="onBlur"
            @focus="onFocus"
            :readonly="readonly"
            type="password"
            v-model="ruleForm.password"
            show-password
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item class="codeKey">
          <!--验证码验证 prop="verify" -->
          <el-input
            type="text"
            :readonly="loading"
            v-model="ruleForm.verify"
            @keyup.enter.native="submitForm('ruleForm')"
            prefix-icon="el-icon-key"
            placeholder="验证码"
            clearable
          >
            <template slot="append">
              <div @click="refreshCode">
                <Identify :identifyCode="identifyCode"></Identify>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-checkbox v-model="checked" class="remember">记住密码</el-checkbox>
        <el-form-item>
          <div style="display: flex;justify-content: space-between;">
            <el-button class="submitBtn" @click="resetForm('ruleForm')" size="small">
              <span class="el-icon-refresh-right" style="margin-right: 8px;"></span>
              重 置
            </el-button>
            <el-button
              class="submitBtn"
              type="primary"
              @click="submitForm('ruleForm')"
              size="small"
              :loading="loading"
            >
              <span class="el-icon-right" style="margin-right: 8px;" v-show="!loading"></span>
              {{loading?'登录中...':'登 录'}}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <p class="footer_top">
        <span class="footer_title">Copyright&nbsp;@墨狐体育科技 版权所有</span>
        <span class="footer_link">浙ICP备 19009304号-2</span>
      </p>
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010802010596"
        target="_blank"
        class="footer_bottom"
      >
        <img
          src="../assets/img/records.png"
          alt
          style="width: 16px;height: 16px;margin-right: 5px;"
        />
        <span class="footer_a">浙公网安备 33010802010596号</span>
      </a>
    </div>
  </div>
</template>

<script>
import Identify from "@/components/Identify";
import md5 from "js-md5";
import Router from "vue-router";
// import router, { asyncRouterMap, constantRouterMap, all } from "../router";
import { login, MAIN } from "../utils/api";
import { Flatten } from "../utils/common";

export default {
  name: "Login",
  data() {
    const validatePass = (rule, value, callback) => {
      let reg = /^[A-Za-z0-9]+$/;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!reg.test(value)) {
        callback(new Error("只能输入数字和字母"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (value.toLowerCase() !== this.identifyCode.toLowerCase()) {
        this.refreshCode();
        callback(new Error("请输入正确的验证码"));
      } else {
        callback();
      }
    };
    return {
      title: "Express delivery",
      readonly: true,
      loading: false,
      checked: true, //记住密码
      identifyCodes: "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
      identifyCode: "",
      ruleForm: {
        password: "",
        username: "",
        verify: ""
      },
      rules: {
        password: [{ validator: validatePass, trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        verify: [{ validator: validateCode, trigger: "blur" }]
      },
      locker: null
    };
  },
  created() {
    this.$store.dispatch("logout").then(res => {
      let that = this;
      that.$store.commit("SAVE");
      that.identifyCode = "";
      that.makeCode(that.identifyCodes, 4);
      that.locker = setInterval(() => {
        that.refreshCode();
      }, 60000);
    });
  },
  mounted() {
    this.getCookie();
  },
  methods: {
    onFocus() {
      this.readonly = false;
    },
    onBlur() {
      this.readonly = true;
    },
    // 登录
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //判断复选框是否被勾选 勾选则调用配置cookie方法
          if (this.checked === true) {
            // console.log("checked == true");
            //传入账号名，密码，和保存天数3个参数
            this.setCookie(this.ruleForm.username, this.ruleForm.password, 7);
          } else {
            //清空Cookie
            this.clearCookie();
          }
          const params = {
            pet_name: this.ruleForm.username,
            password: this.ruleForm.password // md5加密
          };
          this.loading = true;

          // setTimeout(() => {
          //   this.loading = false;
          //   this.refreshCode();
          //   //生成token和用户信息并存储
          //   let token = "";
          //   for (let i = 0; i < 6; i++) {
          //     token += this.identifyCodes[
          //       this.randomNum(0, this.identifyCodes.length)
          //     ];
          //   }
          //   localStorage.setItem(
          //     "userinfo",
          //     JSON.stringify({ username: params.username, token })
          //   );
          //   this.permission();
          // }, 1000);

          this.postRequest(login, params, MAIN).then(res => {
            this.loading = false;
            if (res.code == 200) {
              // console.log(res.data);
              sessionStorage.setItem("userInfo", JSON.stringify(res.data));
              // let menuArr = []; //所有的权限
              // let menu = res.data.menu;
              // for (let x in menu) {
              //   // console.log(menu[x]);
              //   menuArr.push(menu[x].node_url);
              //   if (menu[x].child) {
              //     // console.log(menu[x].child);
              //     for (let y in menu[x].child) {
              //       // let y = 0; y < menu[x].child.length; y++
              //       // console.log(menu[x].child[y].node_name);
              //       menuArr.push(menu[x].child[y].node_url);
              //       if (menu[x].child[y].child) {
              //         // console.log(menu[x].child[y].child);
              //         for (let z in menu[x].child[y].child) {
              //           // console.log(menu[x].child[y].child[z].node_url)
              //           if(menu[x].child[y].child[z].node_url.substring(0, 1) == "/"){
              //           // console.log(menu[x].child[y].child[z].node_url)
              //             menuArr.push(menu[x].child[y].child[z].node_url);
              //           }
              //         }
              //       }
              //     }
              //   }
              // }
              // menuArr.unshift("/Index");
              // // return false;
              // this.permission(menuArr);
              // this.permission(menuArr);
              let menuArray = Flatten(res.data.menu, "child", true);
              // 进行处理数组
              let handleMenu = menuArray.map(v => {
                return {
                  id: v.id,
                  parentId: v.f_id,
                  title: v.node_name,
                  sort: v.sort,
                  path: v.node_url
                };
              });
              // // console.log(handleMenu)
              // let parentIdArr = [];//父级
              // for (let i = 0; i < handleMenu.length; i++) {
              //   if (handleMenu[i].parentId == 0) {
              //     parentIdArr.push(handleMenu[i]);
              //   } else {
              //     parentIdArr = [];
              //   }
              // }
              // console.log(parentIdArr);
              // let ChildrenArr = [];
              // for (let i = 0; i < handleMenu.length; i++) {
              //   for(let j = 0; j < parentIdArr.length; j++){
              //     if(parentIdArr[j].parentId == handleMenu[i].id){
              //       console.log()
              //     }
              //   }

              // }

              const parent = handleMenu.filter(v => v.parentId === 0);

              const menus = transform(parent, handleMenu);
              //一维数组转多维数组
              function transform(data, list) {
                for (let i = 0; i < data.length; i++) {
                  data[i].children = [];
                  for (let j = 0; j < list.length; j++) {
                    if (data[i].id === list[j].parentId) {
                      const parent = list.filter(
                        v => data[i].id === v.parentId
                      );
                      transform(parent, list);
                      data[i].children.push(list[j]);
                    }
                  }
                }
                return data;
              }
console.log(menus)
              this.permission(JSON.parse(JSON.stringify(menus)));
            }
          });
        } else {
          return false;
        }
      });
    },
    //权限及导航栏过滤拦截
    permission(list) {
      console.log(list);
      if (!list || list === null || list === "" || list.length === 0) {
        Warning("未分配权限,请联系管理员.");
        return;
      }
      sessionStorage.setItem("list", JSON.stringify(list));
      this.$store.dispatch("filterMenus", list).then(() => {
        this.$store.dispatch("filterRouter", list).then(obj => {
          console.log(obj)
          console.log(this.$router.options);
          this.$router.replace('/LockerList');
        });
      });
    },
    // 页面权限处理
    // permission(res) {

    //   // const admin = [
    //   //   "/Index",
    //   //   "/Home",
    //   //   "/Member",
    //   //   "/MemberControl",
    //   //   "/BannerList",
    //   //   "/Goods",
    //   //   "/GoodsList",
    //   //   "/Taste",
    //   //   "/Sku",
    //   //   "/Cate",
    //   //   "/MenuSkuList",
    //   //   "/MenuTastes",
    //   //   "/Project",
    //   //   "/ProjectList",
    //   //   "/Discount",
    //   //   "/DiscountList",
    //   //   "/Locker",
    //   //   "/LockerList",
    //   //   "/BoxList",
    //   //   "/SizeList",
    //   //   "/Deliver",
    //   //   "/DeliverList",
    //   //   "/DeliverLockerList",
    //   //   "/Order",
    //   //   "/MenuOrders",
    //   //   "/DeliverOrders",
    //   //   "/StoreLog",
    //   //   "/Role",
    //   //   "/AuthRole",
    //   //   "/AuthUser",
    //   //   "/AuthMenu"
    //   // ]; //admin权限列表
    //   // const test = [
    //   //   "/Index",
    //   //   "/Home",
    //   //   "/Member",
    //   //   "/MemberControl",
    //   //   "/BannerList",
    //   //   "/Goods",
    //   //   "/GoodsList",
    //   //   "/Taste",
    //   //   "/Sku",
    //   //   "/Cate",
    //   //   "/MenuSkuList",
    //   //   "/MenuTastes",
    //   //   "/Project",
    //   //   "/ProjectList",
    //   //   "/Discount",
    //   //   "/DiscountList",
    //   //   "/Locker",
    //   //   "/LockerList",
    //   //   "/BoxList",
    //   //   "/SizeList",
    //   //   "/Deliver",
    //   //   "/DeliverList",
    //   //   "/DeliverLockerList"
    //   // ]; //test权限列表
    //   // const limit =
    //   //   this.ruleForm.username === "admin"
    //   //     ? admin
    //   //     : this.ruleForm.username === "test"
    //   //     ? test
    //   //     : [];
    //   const limit = res;
    //   const index = this.$store.state.index;
    //   const list = []; //拥有权限路由集合
    //   //过滤动态路由
    //   const async = JSON.parse(JSON.stringify(asyncRouterMap));
    //   async.forEach(item => {
    //     if (limit.indexOf(item.path) > -1) {
    //       //判断动态路由中是否存在权限
    //       list.push(item); //存在权限,就将路由信息添加到新数组
    //       if (Array.isArray(item.children)) {
    //         //判断动态路由中是否拥有子级,如果有子级再判断子级路由中是否存在权限,如果存在就将路由信息添加到新数组
    //         const path = item.children.map(self => self.path);
    //         const arr = []; //所有拥有的子级路由
    //         path.forEach((v, i) => {
    //           if (limit.indexOf(v) > -1) arr.push(item.children[i]);
    //         });
    //         item.children = arr;
    //       }
    //     }
    //     if (item.path === "*") {
    //       list.push(item);
    //     }
    //   });
    //   //递归循环获取路由的component,缓存中无法缓存component
    //   all.forEach(item => {
    //     function recursion(arr) {
    //       arr.forEach(self => {
    //         if (item.path === self.path && item.component) {
    //           self.component = item.component;
    //         }
    //         if (Array.isArray(self.children)) {
    //           recursion(self.children);
    //         }
    //       });
    //     }

    //     recursion(list);
    //   });
    //   if (list.map(v => v.path).indexOf(index) > -1) {
    //     const options = constantRouterMap.concat(list);
    //     localStorage.setItem("routes", JSON.stringify(options)); //存储路由
    //     console.log(list)
    //     this.loading = true;
    //     router.matcher = new Router({ mode: "hash" }).matcher;
    //     router.addRoutes(options);
    //     router.options.routes = options;
    //     this.$store.dispatch("initMenus").then(obj => {
    //       this.loading = false;
    //       // router.push(obj.Home.path);
    //     });
    //   } else {
    //     this.$notify({
    //       title: "警告",
    //       message: "当前用户没有权限",
    //       type: "warning"
    //     });
    //     return false;
    //   }
    // },
    //重置
    resetForm(formName) {
      this.clearCookie();
      this.$refs[formName].resetFields();
    },
    // 图形验证码
    randomNum(min, max) {
      // console.log(min);
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    //生成验证码
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += o[this.randomNum(0, o.length)];
      }
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      let exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    //读取cookie
    getCookie() {
      if (document.cookie.length > 0) {
        let arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (let i = 0; i < arr.length; i++) {
          let arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] === "userName") {
            this.ruleForm.username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] === "userPwd") {
            this.ruleForm.password = arr2[1];
          }
        }
      }
    },
    //清除cookie
    clearCookie() {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    }
  },
  components: {
    Identify
  }
};
</script>

<style scoped>
.bg {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
}

.title {
  font-size: 18px;
  padding-left: 20px;
  padding-top: 20px;
}

.login {
  position: absolute;
  z-index: 2;
  left: 50%;
  top: 45%;
  width: 350px;
  height: 340px;
  margin-top: -175px;
  margin-left: -170px;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  background: #fff;
  overflow: hidden;
}

.ruleForm {
  padding: 20px;
}

/*验证码*/
.codeKey {
  width: 100%;
  display: flex;
  align-items: center;
}

.remember {
  margin-bottom: 15px;
}

.submitBtn {
  width: 50%;
  letter-spacing: 1px;
  font-size: 16px;
}

.codeKey >>> .el-input-group__append {
  padding: 0;
}

#iframe {
  background-color: transparent;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
}

.footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 10px;
  z-index: 2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 45px;
}

.footer_top {
  display: flex;
  align-items: center;
  justify-content: center;
}

.footer_title {
  font-size: 12px;
  color: rgb(226, 228, 233);
}

.footer_link {
  font-size: 12px;
  text-decoration: none;
  color: rgb(226, 228, 233);
  margin-left: 10px;
}

.footer_bottom {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: rgb(226, 228, 233);
  font-size: 12px;
  margin-top: 5px;
}
</style>
